﻿using System.Reflection;

using ApproveFlowEngine.Split;

namespace ApproveFlowEngine.EntityFrameworkCoreSplitTable.Tools
{
    public static class SplitTableHelper
    {
        #region Public Methods

        public static SplitTableAttribute? GetSplitAttribute(Type type)
        {
            foreach (var prop in type.GetProperties())
            {
                var attr = prop.GetCustomAttribute<SplitTableAttribute>();
                if (attr is not null)
                {
                    return attr;
                }
            }
            return default;
        }

        public static string GetTail(this ISplitTable splitTable)
        {
            var type = splitTable.GetType();
            foreach (var prop in type.GetProperties())
            {
                var attr = prop.GetCustomAttribute<SplitTableAttribute>();
                if (attr is not null)
                {
                    var value = prop.GetValue(splitTable);
                    if (DateTime.TryParse(value?.ToString(), out var dateTime))
                    {
                        return attr.GetTail(dateTime);
                    }
                }
            }
            return string.Empty;
        }

        public static string GetTail<T>(DateTime dateTime) where T : ISplitTable
        {
            var type = typeof(T);
            var attr = GetSplitAttribute(type);
            if (attr is null)
            {
                return string.Empty;
            }
            return attr.GetTail(dateTime);
        }

        public static List<string> GetTails<T>(List<string> tails, DateTime? begin = null, DateTime? end = null) where T : ISplitTable
        {
            var type = typeof(T);
            var attr = GetSplitAttribute(type);
            if (attr is null)
            {
                return new List<string>();
            }
            else
            {
                return attr.FilterTail(begin, end, tails);
            }
        }

        #endregion Public Methods
    }
}